import {useEffect, useRef} from "react";
import {Link as NavLink} from 'react-router-dom'
import {apiLogout} from "@/common/apis/user";
import {message} from "antd";
import {clearLocalStorage, getToken} from "@/common/util";
import UserInfoStore from "@/common/store/UserInfoStore";
import {observer} from "mobx-react";

interface UserProps {
  openLoginModel: () => void
  activeCate: number
}

function User(props: UserProps) {

  let menuItSelf = useRef<any>()

  useEffect(() => {
    UserInfoStore.queryUserInfo()
    document.addEventListener(`click`, closeMenu)
  }, [])

  /**
   * 如果没登陆就回调出去，登陆了就显示个人信息
   */
  function handleClick(e: any) {
    e.stopPropagation()
    const token = getToken()
    if (!token) {
      props.openLoginModel()
      return;
    }
    openMenu()
  }

  // 关闭/显示用户下拉菜单
  function openMenu() {
    menuItSelf.current.style.display = 'block'
  }

  function closeMenu() {
    if (!!menuItSelf && menuItSelf.current.style.display !== 'none') {
      menuItSelf.current.style.display = 'none'
    }
  }

  function gotoMyhome() {
    console.log('-------gotoMyhome-----------')
    closeMenu()
  }

  function logOut() {
    apiLogout().then(res => {
      console.log(res)
      if (res.code == 0) {
        message.success({content: '退出成功', duration: 0.5}).then(r => {
          closeMenu()
          clearLocalStorage()
          window.location.href = '/home'
          // window.location.reload()
        })
      }
    })
  }

  return (
    <div className='user' onClick={(e) => handleClick(e)}>

      <div className='avatar' style={{backgroundImage: `url(${UserInfoStore.Avatar})`}}/>

      <div
        ref={menuItSelf}
        className='menu'
        style={{display: 'none'}}
        onClick={gotoMyhome}
      >
        <NavLink className='user-btn' to={'/myhome'}>
          个人中心
        </NavLink>
        <div className='user-btn' onClick={logOut}>退出登录</div>
      </div>
    </div>
  )
}

export default observer(User)
